/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package teacher;

import common.MessageModel;
import java.io.BufferedInputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import javax.swing.JLabel;

/**
 * 子服务线程，用来持续接收来自学生端的消息
 *
 * @author Eugene-Forest
 */
public class SubTeacherThread extends Thread {

    private Socket socket;
    private ObjectInputStream in;
    private JLabel hadReadLabel, onlineLabel;

    public SubTeacherThread(Socket socket, JLabel hadReadLabel, JLabel onlineLabel) {
        this.socket = socket;
        //初始化组件变量
        this.hadReadLabel = hadReadLabel;
        this.onlineLabel = onlineLabel;
    }

    @Override
    public void run() {
        try {
            MessageModel messageModel;
            //事先定义一个bufferedInputStream对象转换InputStream对象以减少频繁创建ObjectInputStream时造成的资源浪费
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            while (true) {
                in = new ObjectInputStream(bis);
                messageModel = (MessageModel) in.readObject();
                if (messageModel != null) {
                    switch (messageModel.getType()) {
                        case Finish:
                            //判断校验码是否是最新的
                            if (messageModel.get_auth_code().equals(DataCenter.get_auth_code())) {
                                DataCenter.count_plus();
                                hadReadLabel.setText(String.valueOf(DataCenter.get_counts()));
                            }
                            break;
                        case Review:
                            new NoticeThread(socket).start();
                            break;
                        case Finish_Quit:
//                            DataCenter.count_sub();
//                            hadReadLabel.setText(String.valueOf(DataCenter.get_counts()));
                            break;
                        case Quit:
                            break;
                        default:
                            break;
                    }
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
            //remove this scoket from socket list，更新名字列表
            DataCenter.remove_socket(socket);
            onlineLabel.setText(String.valueOf(DataCenter.get_sockets_size()));
        }
    }

}
